package com.zhouyibike.uu.ui.activity;

import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.squareup.picasso.Picasso;
import com.zhouyibike.uu.R;
import com.zhouyibike.uu.config.Config;
import com.zhouyibike.uu.entity.GetCodeResult;
import com.zhouyibike.uu.http.ApiCallback;
import com.zhouyibike.uu.ui.activity.mywallet.ChongzhimimaActivity1;
import com.zhouyibike.uu.ui.base.BaseActivity;
import com.zhouyibike.uu.ui.view.TXCircleImageView;
import com.zhouyibike.uu.util.BitmapUtil;
import com.zhouyibike.uu.util.CommonUtil;
import com.zhouyibike.uu.utils.Base64Encoder;
import com.zhouyibike.uu.utils.FileUtil;
import com.zhouyibike.uu.utils.ImgUtils;
import com.zhouyibike.uu.utils.PhoneUtils;
import com.zhouyibike.uu.utils.TextUtils;
import com.zhouyibike.uu.utils.TimeUtils;
import com.zhouyibike.uu.utils.UploadUtil;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class MineActivity extends BaseActivity implements View.OnClickListener {
    private ImageButton mBtnBack;
    private TextView mBtnTitle;

    private LinearLayout ll_head, ll_nickname, ll_state, chongzhimimaly;
    private TXCircleImageView txciv_head;
    private Button btn_logout;
    private TextView tv_nickname, tv_tel, tv_state;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mine);
        initView();
        initData();
    }

    private void initView() {
        chongzhimimaly = (LinearLayout) findViewById(R.id.chongzhimimaly);
        mBtnBack = (ImageButton) findViewById(R.id.bar_btn_back);
        mBtnTitle = (TextView) findViewById(R.id.bar_text_title);
        mBtnTitle.setText("个人中心");
        mBtnBack.setOnClickListener(this);
        ll_head = (LinearLayout) findViewById(R.id.ll_mine_head);
        ll_head.setOnClickListener(this);
        ll_nickname = (LinearLayout) findViewById(R.id.ll_mine_nickname);
        ll_nickname.setOnClickListener(this);
        ll_state = (LinearLayout) findViewById(R.id.ll_mine_state);
        ll_state.setOnClickListener(this);
        tv_nickname = (TextView) findViewById(R.id.tv_mine_nickname);
        tv_tel = (TextView) findViewById(R.id.tv_mine_tel);
        tv_state = (TextView) findViewById(R.id.tv_mine_state);
        txciv_head = (TXCircleImageView) findViewById(R.id.txciv_mine_headimg);
        btn_logout = (Button) findViewById(R.id.btn_logout);
        btn_logout.setOnClickListener(this);
        chongzhimimaly.setOnClickListener(this);
    }

    private void initData() {
        if (preferences.getString("status", "").equals("0")) {
            tv_state.setText("未骑行充值");

        } else if (preferences.getString("status", "").equals("1")) {
            tv_state.setText("未认证");

        } else if (preferences.getString("status", "").equals("3")) {
            tv_state.setText("已认证");
        }
        try {
//            Picasso.with(this).load("http://www.pqsas.com/pqsas/uploadFiles/uploadImgs/pqarea/20170908/1314.png").into(txciv_head);
            //图片过大需压缩
            Picasso.with(this).load(preferences.getString("headPicture", "")).transform(ImgUtils.Picassocompress(txciv_head)).error(R.mipmap.head_moren).placeholder(R.mipmap.head_moren).into(txciv_head);
        } catch (Exception e) {

        }
        if (!TextUtils.isNullorEmpty(preferences.getString("nickName", ""))) {
            tv_nickname.setText(preferences.getString("nickName", ""));
        } else{
            tv_nickname.setText("");
        }
//        else if (!TextUtils.isNullorEmpty(preferences.getString("fullName", ""))) {
//          //  tv_nickname.setText(preferences.getString("fullName", ""));
//        } else {
//           // tv_nickname.setText(TextUtils.toFormatPhone(preferences.getString("mobile", "")));
//        }
      //  tv_tel.setText(TextUtils.toFormatPhone(preferences.getString("mobile", "")));
        tv_tel.setText((preferences.getString("mobile", "")));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.chongzhimimaly:
                startActivityForResult(new Intent(MineActivity.this, ChongzhimimaActivity1.class), 1001);
                break;
            case R.id.bar_btn_back:
                finish();
                break;
            case R.id.ll_mine_state:
                if (preferences.getString("status", "").equals("3")) {

                } else {
                    startActivityForResult(new Intent(MineActivity.this, YanzhengActivity.class), 100);
                }
                break;
            case R.id.ll_mine_nickname:
                startActivityForResult(new Intent(MineActivity.this, ModifyNickNameActivity.class), 100);
                break;
            case R.id.ll_mine_head:
                showPopupWindow(v);
                break;
            case R.id.btn_take_photo:
                popupWindow.dismiss();
//                if (PermissionUtils.isCameraPermission(MineActivity.this, 0x007)){
                byCamera();
//                }
                break;
            case R.id.btn_pick_photo:
                popupWindow.dismiss();
//                if (PermissionUtils.isCameraPermission(MineActivity.this, 0x009)) {
                //打开相册
                openAlbum();
//                }
                break;
            case R.id.btn_cancel:
                popupWindow.dismiss();
                break;
            case R.id.btn_logout:
                SharedPreferences.Editor editor = preferences.edit();
                editor.clear();
                editor.commit();
                setResult(2);
                finish();
                break;
        }
    }

    private String imagePath;

    //打开相机
    public void byCamera() {
        String savePath = "";
        String storageState = Environment.getExternalStorageState();
        if (storageState.equals(Environment.MEDIA_MOUNTED)) {
            savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/camera/";
            File savedir = new File(savePath);
            if (!savedir.exists()) {
                savedir.mkdirs();
            }
        }

        // 没有挂载SD卡，无法保存文件
        if (savePath == null || "".equals(savePath)) {
            System.out.println("无法保存照片，请检查SD卡是否挂载");
            return;
        }

        String timeStamp = TimeUtils.getCurrentTimeInString();
        //照片命名
        String fileName = timeStamp + ".jpg";
        File out = new File(savePath, fileName);
//        Uri uri = Uri.fromFile(out);
        //该照片的绝对路径
        imagePath = savePath + fileName;
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        ContentValues contentValues = new ContentValues(1);
        contentValues.put(MediaStore.Images.Media.DATA, out.getAbsolutePath());
        Uri uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(intent, 0x008);
    }

    //打开相册
    private void openAlbum() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent, 0x006); // 打开相册
    }

    //请求权限回调
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 0x007:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    byCamera();
                } else {
                    Toast.makeText(this, "拍照权限被拒绝", Toast.LENGTH_SHORT).show();
                }
                break;
            case 0x009:
                if (grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    openAlbum();
                } else {
                    Toast.makeText(this, "相册权限被拒绝", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
    }

    PopupWindow popupWindow;

    private void showPopupWindow(View v) {
        View view = getLayoutInflater().inflate(R.layout.select_tackphoto_type, null);

        popupWindow = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setFocusable(true);

        popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
        backgroundAlpha(0.5f);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1f);
            }
        });
        popupWindow.showAtLocation(this.findViewById(R.id.ll_mine_head),
                Gravity.BOTTOM, 0, PhoneUtils.getBottomStatusHeight(this));
        TextView btn_camera = (TextView) view.findViewById(R.id.btn_take_photo);
        TextView btn_takelocation = (TextView) view.findViewById(R.id.btn_pick_photo);
        TextView btn_cancle = (TextView) view.findViewById(R.id.btn_cancel);
        btn_camera.setOnClickListener(this);
        btn_takelocation.setOnClickListener(this);
        btn_cancle.setOnClickListener(this);
    }

    Bitmap photobtm;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1001 && resultCode == 1) {//重置密码成功
            setResult(1);
            finish();
        }
        if (requestCode == 100 && resultCode == 1) {
            initData();
            setResult(1);
        }
//        if (requestCode == 8 && resultCode == RESULT_OK) {
//            if (imagePath != null) {
//                  starCropPhoto(Uri.fromFile(new File(imagePath)));
//              //  photobtm = BitmapFactory.decodeFile(imagePath);
//              //  new upImage().execute("");
//            }
//        }
//        if (requestCode == 6 && resultCode == RESULT_OK) {
//             starCropPhoto(data.getData());
//           // photobtm = BitmapFactory.decodeFile(FileUtil.getFilePath(this, data.getData()));
//         //   saveHeadPicture();
//        }
//        if (requestCode == 1234 && resultCode == RESULT_OK) {
//            if (data != null) {
//                setPicToView(data);
//            }
//        }
        if (requestCode == 8&& resultCode == RESULT_OK) {
            if(imagePath!=null ){
                photobtm=BitmapFactory.decodeFile(imagePath);
                new upImage().execute("");
            }
        }
        if(requestCode==6&& resultCode == RESULT_OK){
            photobtm=BitmapFactory.decodeFile(FileUtil.getFilePath(this,data.getData()));
            new upImage().execute("");
//            saveHeadPicture();
        }
    }

    private void saveHeadPicture() {
        Map<String, String> params = new HashMap<>();
        params.put("token", preferences.getString("token", ""));
        params.put("fileName", "headname.png");
        params.put("picture", URLEncoder.encode(bitmaptoString(photobtm)));
        showProgressDialog();
        addSubscription(apiStores.SaveHeadPicture(params),
                new ApiCallback<GetCodeResult>() {

                    @Override
                    public void onSuccess(GetCodeResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
                            SharedPreferences.Editor edit = preferences.edit();
                            edit.putString("headPicture", model.getData());
                            edit.commit();
                            initData();
                        } else {
                            toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);

                    }

                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                    }
                });
    }

    class upImage extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPostExecute(String o) {
            try {
                GetCodeResult smsResult = new Gson().fromJson(o, GetCodeResult.class);
                dismissProgressDialog();
                if (smsResult.getStatus() == Config.SUCCESSCODE) {
                    SharedPreferences.Editor edit = preferences.edit();
                    edit.putString("headPicture", smsResult.getData());
                    edit.commit();
                    initData();
                    setResult(1);
                } else {
                    toastShow(smsResult.getMessage());
                }
            } catch (Exception e) {
                toastShow("上传失败");
            }
            super.onPostExecute(o);
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
        }

        @Override
        protected String doInBackground(String... o) {
            String request = "";

            try {
                String pa = "token=" + URLEncoder.encode(preferences.getString("token", ""), "UTF-8") + "&picture=" + URLEncoder.encode(bitmaptoString(photobtm), "UTF-8") + "&fileName=" + URLEncoder.encode("newhead.png", "UTF-8");
                request = UploadUtil.send2(Config.API_SERVER + "v1/SaveHeadPicture/", pa);
            } catch (Exception e) {
                dismissProgressDialog();
                e.printStackTrace();

            }
            return request;
        }

        @Override
        protected void onPreExecute() {
            showProgressDialog();
        }
    }

    public String bitmaptoString(Bitmap bitmap) {
        // 将Bitmap转换成字符串

        String string = "";

        ByteArrayOutputStream bStream = new ByteArrayOutputStream();

        bitmap.compress(Bitmap.CompressFormat.JPEG, 50, bStream);

        byte[] bytes = bStream.toByteArray();
        Base64Encoder base = new Base64Encoder();
        string = base.encode(bytes); //
        return string;
    }

    /**
     * 打开截图界面
     *
     * @param uri 原图的Uri
     */
    public void starCropPhoto(Uri uri) {

        if (uri == null) {
            return;
        }
//        Intent intent = new Intent();
//        intent.setClass(this, ClipHeaderActivity.class);
//        intent.setData(uri);
//        intent.putExtra("side_length", 200);//裁剪图片宽高
//        startActivityForResult(intent, 1234);

        //调用系统的裁剪
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 200);
        intent.putExtra("outputY", 200);
        intent.putExtra("circleCrop", "true");
        intent.putExtra("noFaceDetection", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri1);
        startActivityForResult(intent, 1234);
    }

    private void setPicToView(Intent picdata) {
        //  Uri uri = picdata.getData();
        Uri uri = uri1;
        if (uri == null) {
            return;
        }
        String path = CommonUtil.getRealFilePathFromUri(getApplicationContext(), uri);
        if (android.text.TextUtils.isEmpty(path)) {
            return;
        }
        //原图可能很大，现在手机照出来都3000*2000左右了，直接加载可能会OOM
        //这里 decode 出 720*1280 左右的照片
        photobtm = BitmapUtil.decodeSampledBitmap(path, 720, 1280);
        // iv_head_icon.setImageURI(uri);
        new upImage().execute("");
    }

    Uri uri1 = Uri.fromFile(new File(IMAGE_FILE_LOCATION));
    private static final String IMAGE_FILE_LOCATION = Environment.getExternalStorageDirectory().getAbsolutePath() + "/camera/temp.jpg";
}
